package cn.edu.ujn.lishlab3.controller;


import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import cn.edu.ujn.lishlab3.dao.Orders;
import cn.edu.ujn.lishlab3.service.IOrdersService;
import cn.edu.ujn.lishlab3.service.IProductService;
import cn.edu.ujn.util.Page;

@Controller
public class OrdersController {

	@Autowired
	private IOrdersService ordersService;
	@Autowired
	private IProductService productService;

//
	@RequestMapping(value = "/orders/list.action")
	public String list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows,
			String ordersNumber, Integer cust_id, Model model) {
		Page<Orders> findOrdersList = ordersService.findOrdersList(page, rows, ordersNumber, cust_id);
		List<Orders> list = findOrdersList.getRows();
		for (Orders order : list) {
			order.setProductList(productService.findProductById(order.getId()));
		}
		
		model.addAttribute("page", findOrdersList);
		model.addAttribute("number", ordersNumber);
		model.addAttribute("cust_id", cust_id);
		return "orders";
	}

	// 创建订单
	@RequestMapping("/orders/create.action")
	@ResponseBody
	public String ordersCreate(Orders orders, HttpSession session) {
		int rows = ordersService.insertSelective(orders);
		if (rows > 0) {
			return "OK";
		} else {
			return "FAIL";
		}
	}

	// 通过id获取客户信息
	@RequestMapping("/orders/getOrdersById.action")
	@ResponseBody
	public Orders getOrdersById(Integer id) {
		Orders orders = ordersService.selectByPrimaryKey(id);
//		 System.out.println("++++"+orders.getCust_name()+" "+orders.getId());
		return orders;
	}

	// 更新客户
	@RequestMapping("/orders/update.action")
	@ResponseBody
	public String ordersUpdate(Orders order) {
//		System.out.println("++++"+order.getCust_name()+" "+order.getId());
		int rows = ordersService.updateByPrimaryKeySelective(order);
		if (rows > 0) {
			return "OK";
		} else {
			return "FAIL";
		}
	}

	// 删除用户
	@RequestMapping("/orders/delete.action")
	@ResponseBody
	public String ordersDelete(Integer id) {
		int rows = ordersService.deleteByPrimaryKey(id);
		if (rows > 0) {
			return "OK";
		} else {
			return "FAIL";
		}
	}

}
